<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.id == 0 ? '新增洗衣错衣' : '编辑洗衣错衣'"
      width="500"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 300px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="老人姓名:" prop="elderlyId">
            <el-button @click="handleSelect">
              {{ elderlyName ? elderlyName : "选择老人" }}
            </el-button>
          </el-form-item>
          <el-form-item label="标题:" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="类型:" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择" clearable>
              <el-option label="缺衣" value="缺衣" />
              <el-option label="错衣" value="错衣" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态:" prop="state">
            <el-select v-model="ruleForm.state" placeholder="请选择" clearable>
              <el-option label="未解决" value="未解决" />
              <el-option label="已解决" value="已解决" />
            </el-select>
          </el-form-item>
          <el-form-item label="内容:" prop="content">
            <el-input v-model="ruleForm.content" type="textarea" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label=" ">
            <el-upload
              v-model:file-list="fileList"
              :action="BaseImgUrl"
              :headers="headers"
              :on-change="handleRemove"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button type="primary">上传图片</el-button>
              <template #tip>
                <div class="el-upload__tip">可以上传3张图片</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择老人 -->
    <elderlyDialog v-if="dialogVisibleElder" @close="handleElderly" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { clothesAddParams } from "@/api/care/clothes/type";
import type { UploadProps, UploadUserFile } from "element-plus";
import elderlyDialog from "@/components/market/discharge/selectElderly.vue";
import { getToken } from "@/utils/auth";
import { clothesAdd, clothesGet, clothesUpdate } from "@/api/care/clothes/clothes";

const dialogVisible = ref(true);
const dialogVisibleElder = ref(false);

const props = defineProps({
  listParams: Number,
});
let id = props.listParams as number;

// 图片根路径
const BaseImgUrl = import.meta.env.VITE_APP_API_URL + "/api/upload/add";
const headers = { Authorization: getToken() };
const imgUrl = import.meta.env.VITE_IMG_URL;

const ruleForm = reactive<clothesAddParams>({
  id: 0,
  elderlyId: undefined,
  title: "",
  content: "",
  type: "",
  state: "",
  pictures: [],
});

// 老人
const elderlyName = ref("");
const handleSelect = () => {
  dialogVisibleElder.value = true;
};
const handleElderly = (val: any) => {
  ruleForm.elderlyId = val.id;
  elderlyName.value = val.name;
  dialogVisibleElder.value = false;
};

// 获取单条数据
const getData = async () => {
  let res = await clothesGet(id);
  // console.log(res);
  Object.assign(ruleForm, res);
  elderlyName.value = res.elderlyName;
  fileList.value = res.pictures.map((item) => ({ name: item.file, url: imgUrl + item.file }));
};

// 添加
const submitForm = async () => {
  await clothesAdd(ruleForm);
  // console.log('添加', res);
  ElMessage.success("添加成功");
  emit("handelClose");
};

// 修改
const update = async () => {
  await clothesUpdate(ruleForm);
  // console.log('修改', res);
  ElMessage.success("修改成功");
  emit("handelClose");
};

const submit = () => {
  let imgs = fileList.value.map((item: any) =>
    item.response ? item.response.data.url : item.name
  );
  ruleForm.pictures = imgs.map((item) => ({ file: item }));

  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      ruleForm.id === 0 ? await submitForm() : await update();
    }
  });
};

// 上传图片
const fileList = ref<UploadUserFile[]>([]);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  if (fileList.value.length > 3) {
    fileList.value.splice(3);
    ElMessage.warning("最多上传三张图片");
  }
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<clothesAddParams>>({
  elderlyId: [{ required: true, message: "请选择老人", trigger: "change" }],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  state: [{ required: true, message: "请选择状态", trigger: "change" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
});

// 关闭弹窗
const emit = defineEmits(["handelClose"]);
const handleClose = () => {
  emit("handelClose");
};

onMounted(() => {
  getData();
});
</script>

<style scoped lang="less"></style>
